package com.buddy.qreport.query.interceptor;

import com.buddy.qreport.query.dao.IQueryMapper;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName DynamicSelectInterceptor
 * @Descriptin TODO
 * @Author Skippyb
 * @Date 2019/4/23 15:15
 * @Version 1.0
 **/
@Intercepts({

        @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(method = "query", type = Executor.class, args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),

})

@Component
public class DynamicSelectInterceptor implements Interceptor {
    
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Executor executor = (Executor) invocation.getTarget();
        Object[] args = invocation.getArgs();

        MappedStatement mappedStatement = (MappedStatement) args[0];
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        String id = mappedStatement.getId();
        int i = id.lastIndexOf(".");
        String className = id.substring(0,i);
        String methodName = id.substring(i + 1,id.length());

        if (IQueryMapper.class.getName().equals(className) && "dynamicSelect".equals(methodName)) {
            Map queryParams = (Map)args[1];
            String sql = (String)queryParams.get("sql");
            Configuration configuration = mappedStatement.getConfiguration();
            BoundSql boundSql = null;
            if (sql.startsWith("<script>")) {
                LanguageDriver defaultDriver = configuration.getLanguageRegistry().getDefaultDriver();
                SqlSource sqlSource = defaultDriver.createSqlSource(configuration, sql, Map.class);
                boundSql = sqlSource.getBoundSql(queryParams);
                CacheKey cacheKey = executor.createCacheKey(mappedStatement,queryParams,rowBounds,boundSql);

                List queryResult = executor.query(mappedStatement,queryParams,rowBounds,resultHandler,cacheKey,boundSql);
                return queryResult;
            }

        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
         return Plugin.wrap(target,this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
